<template>
    <div class="production-filter">
        <el-checkbox-group v-model="option">
            <el-checkbox label="未加入生产列表" value="false" />
            <el-checkbox label="已加入生产列表" value="true" />
        </el-checkbox-group>
    </div>
    <div v-if="data.length != 0" class="production-list">
        <div style="width: 100%; height: calc(100vh - 310px)">
            <el-auto-resizer>
                <template #default="{ height }">
                    <el-scrollbar :height="height">
                        <el-descriptions title="数据列表" :column="4" border>
                            <template #extra>
                                <el-text type="warning" tag="b">当前有{{ total }}条数据</el-text>
                            </template>
                            <div v-for="(item, index) in data" :key="index">
                                <!-- 产品名称 -->
                                <el-descriptions-item>
                                    <template #label>
                                        <div class="flex items-center">
                                            <el-icon class="el-icon--left"><BrandProducthunt /></el-icon>
                                            产品名称
                                        </div>
                                    </template>
                                    <el-popover
                                        placement="right"
                                        title="产品详情"
                                        :width="200"
                                        trigger="click"
                                        @before-enter="loadProductionProces(item.customerId, item.productId)"
                                        @after-leave="resetProductionProces"
                                    >
                                        <template #reference>
                                            <div>
                                                <el-button plain :icon="BookQuestionMark20Regular">{{ item.productName }} </el-button>
                                                <el-text tag="b" type="primary"> * {{ item.purchaseNumber }}只</el-text>
                                            </div>
                                        </template>
                                        <template #default>
                                            <div class="flex flex-wrap gap-2">
                                                <el-text class="w-full" tag="b">包装类型：{{ popoverBoxType }}</el-text>
                                                <el-text class="w-full" tag="b">生产工艺：{{ popoverProcess }}</el-text>
                                                <el-text class="w-full" tag="b">产品描述：{{ popoverDescription }}</el-text>
                                            </div>
                                        </template>
                                    </el-popover>
                                </el-descriptions-item>
                                <!-- 订单状态 -->
                                <el-descriptions-item>
                                    <template #label>
                                        <div class="flex items-center">
                                            <el-icon class="el-icon--left"><Book /></el-icon>
                                            订单状态
                                        </div>
                                    </template>
                                    <el-text :type="item.orderStatus" tag="b">{{ matchOrderStatus(item.orderStatus) }}</el-text>
                                </el-descriptions-item>
                                <!-- 采购状态 -->
                                <el-descriptions-item>
                                    <template #label>
                                        <div class="flex items-center">
                                            <el-icon class="el-icon--left"><AiStatusInProgress /></el-icon>
                                            采购状态
                                        </div>
                                    </template>
                                    {{ item.arrivalDate == null ? '未到货' : formatTimeZone(item.arrivalDate, 'YYYY-MM-DD') }}
                                </el-descriptions-item>
                                <!-- 交货日期 -->
                                <el-descriptions-item>
                                    <template #label>
                                        <div class="flex items-center">
                                            <el-icon class="el-icon--left"><Arrival /></el-icon>
                                            交货日期
                                        </div>
                                    </template>
                                    <b :class="matchOrderRemainingDeliveryTime(item.orderDeliveryDate as string)">{{
                                        item.orderDeliveryDate == '暂无送货计划' || item.orderDeliveryDate == null
                                            ? '/'
                                            : formatTimeZone(item.orderDeliveryDate as unknown as Date, 'YYYY-MM-DD')
                                    }}</b>
                                </el-descriptions-item>
                                <!-- 提交到生产组 -->
                                <el-descriptions-item :span="4" v-if="descriptionsLast == 'false'">
                                    <template #label>
                                        <div class="flex items-center">
                                            <el-icon class="el-icon--left"><ArrowsJoin /></el-icon>
                                            <el-text type="primary">审核</el-text>
                                        </div>
                                    </template>
                                    <div class="flex">
                                        <el-checkbox-group v-model="item.productionType">
                                            <el-checkbox label="外箱生产" value="outerbox" />
                                            <el-checkbox label="外箱打包" value="packouterbox" />
                                            <el-checkbox label="裱瓦生产" value="backing" />
                                            <el-checkbox label="模切生产" value="diecutting" />
                                            <el-checkbox label="内盒生产" value="innerbox" />
                                            <el-checkbox label="内盒打包" value="packinnerbox" />
                                        </el-checkbox-group>
                                        <el-button
                                            class="ml-4"
                                            type="primary"
                                            plain
                                            @click="submitProductionEvent(item._id, item.productionType, item.arrivalDate)"
                                        >
                                            提交生产
                                        </el-button>
                                        <el-button class="ml-4" type="warning" plain @click="submitWarehouseEvent(item._id)"> 直接入库 </el-button>
                                    </div>
                                </el-descriptions-item>
                                <!-- 撤回生产组 -->
                                <el-descriptions-item :span="4" v-if="descriptionsLast == 'true'">
                                    <template #label>
                                        <div class="flex items-center">
                                            <el-icon class="el-icon--left"><ArrowStepInLeft28Regular /></el-icon>
                                            <el-text type="warning">撤回</el-text>
                                        </div>
                                    </template>
                                    <el-button plain type="warning" @click="revokeProductionEvent(item._id)">撤回</el-button>
                                </el-descriptions-item>
                                <!-- 占位 -->
                                <el-descriptions-item :span="4" v-if="descriptionsLast == 'none'">
                                    <template #label>
                                        <div class="flex items-center">
                                            <el-icon class="el-icon--left"><HandStop /></el-icon>
                                            <el-text type="danger">禁止操作</el-text>
                                        </div>
                                    </template>
                                    切换 <el-text type="danger">单一生产列表</el-text> 后再进行后续操作
                                </el-descriptions-item>
                            </div>
                        </el-descriptions>
                    </el-scrollbar>
                </template>
            </el-auto-resizer>
        </div>
    </div>
    <div v-if="data.length === 0" style="width: 100%; height: calc(100vh - 310px)">
        <el-empty description="暂无数据"></el-empty>
    </div>
    <div class="production-pagination">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            @change="handleSizeChange"
            :total="total"
            :page-sizes="[20, 40, 80, 100]"
            layout="prev, pager, next, sizes, jumper, total"
            background
        />
    </div>
</template>

<script setup lang="ts">
import { createProductionControl, getProductionControlList, revokeProductionControl } from '@/api/production';
import { BrandProducthunt, ArrowsJoin, HandStop } from '@vicons/tabler';
import { AiStatusInProgress, Book, Arrival } from '@vicons/carbon';
import { BookQuestionMark20Regular, ArrowStepInLeft28Regular } from '@vicons/fluent';
import { formatTimeZone } from '@utils/calculate';
import { getProductInfo } from '@/api/product';

onMounted(() => {
    // 获取采购未被管控的数据
    getProductionControlListEvent();
});

/* ******************************通用属性/方法****************************** */
// 筛选条件 false 未加入生产列表 / true 已加入生产列表
const option = ref(['false']);
// 监听筛选条件变化
watch(
    () => option.value,
    () => {
        getProductionControlListEvent();
    }
);

// 展示数据
const data = reactive<AjaxResponse['purchaseList']>([]);
// 获取对应生产表单数据
const getProductionControlListEvent = () => {
    // 判断极值
    if (option.value.length == 0) {
        return;
    }
    // 清空数据
    data.length = 0;
    // 获取数据
    getProductionControlList(option.value, currentPage.value, pageSize.value).then((res) => {
        total.value = res.total;
        res.data.forEach((item) => {
            item.productionType = [];
            data.push(item);
        });
    });
};

// 提交到生产列表
const submitProductionEvent = (
    purchaseId: string,
    productionType: AjaxRequest['productionControlForm']['productionType'],
    arrivalDate: Date | null
) => {
    if (productionType.length == 0) {
        ElMessage.warning('请选择生产类型');
        return;
    }
    if (!arrivalDate) {
        ElMessage.warning('没有到货的产品，禁止提交');
        return;
    }
    // 提交到生产列表
    createProductionControl({ purchaseId, productionType }).then((res) => {
        ElMessage.success(res.message);
        // 重新获取数据
        getProductionControlListEvent();
    });
};
// 提交到仓库
const submitWarehouseEvent = (purchaseId: string) => {
    // 提交到仓库
    createProductionControl({ purchaseId, productionType: ['warehouse'] }).then((res) => {
        ElMessage.success(res.message);
        // 重新获取数据
        getProductionControlListEvent();
    });
};
// 撤销到生产列表
const revokeProductionEvent = (purchaseId: string) => {
    revokeProductionControl(purchaseId).then((res) => {
        ElMessage.success(res.message);
        // 重新获取数据
        getProductionControlListEvent();
    });
};

/* ******************************描述列表相关属性/方法****************************** */
// 描述列表最后一列变化
const descriptionsLast = computed(() => {
    if (option.value.length == 0) {
        data.length = 0;
    }
    if (option.value.length == 2) {
        return 'none';
    }
    if (option.value.includes('true')) {
        return 'true';
    }

    if (option.value.includes('false')) {
        return 'false';
    }
});
// 生产工艺展示
const popoverBoxType = ref('');
const popoverProcess = ref('');
const popoverDescription = ref('');
// popover 显示动画播放前触发
const loadProductionProces = (customerId: string, productId: string) => {
    getProductInfo(customerId, productId).then((res) => {
        popoverBoxType.value = res.data.boxType;
        popoverProcess.value = res.data.process;
        popoverDescription.value = res.data.description;
    });
};
// 重置数据
const resetProductionProces = () => {
    popoverBoxType.value = '加载中...';
    popoverProcess.value = '加载中...';
    popoverDescription.value = '加载中...';
};

/* ******************************分页相关属性/方法****************************** */
// 当前页码
const currentPage = ref(1);
// 每页显示条数
const pageSize = ref(10);
// 数据的总数
const total = ref(0);
// 监听页码变化
const handleSizeChange = () => {
    getProductionControlListEvent();
};

/* ******************************工具相关属性/方法****************************** */
// 匹配订单状态
const matchOrderStatus = (status: 'primary' | 'warning' | 'danger') => {
    let obj = {
        primary: '正常',
        warning: '加急',
        danger: '特急',
    };
    return obj[status];
};
// 匹配订单剩余送货时间
const matchOrderRemainingDeliveryTime = (time: string) => {
    // 暂无送货计划
    if (time == '暂无送货计划') {
        return 'text-gray-500';
    }
    // 剩余送货时间
    const remainingDeliveryTime = new Date(time).getTime() - new Date().getTime();
    // 剩余送货时间小于24小时，显示红色
    if (remainingDeliveryTime < 24 * 60 * 60 * 1000) {
        return 'text-red-500';
    }
    // 剩余送货时间小于48小时，显示橙色
    if (remainingDeliveryTime < 48 * 60 * 60 * 1000) {
        return 'text-orange-500';
    }
    // 剩余送货时间大于48小时，显示绿色
    return 'text-green-500';
};
</script>

<style scoped lang="scss">
.production-filter {
    height: 50px;
}
.production-list {
    height: calc(100vh - 290px);
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
}
.production-pagination {
    height: 60px;
    width: 100%;
    display: flex;
    align-items: center;
}
</style>
